package com.lmm.test.http.examples.client;
import java.net.URI;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

/**
 * An example that performs GETs from multiple threads.
 *
 */
public class ClientMultiThreaded2Execution {

	private  static final  PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
	private  static  CloseableHttpClient httpclient = null;
	static {
		  cm.setMaxTotal(100);
		  httpclient = HttpClients.custom().setConnectionManager(cm)
          .build(); 
	}
	private static boolean isFound = false;//是否打到
	private static String[] zm = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
	private static String SECTION="9-9";
	private static String CONFIG = "_config.xml";
	//private static String URL_PRIFEX = "http://vv7.51zxw.net/class/proteus/9-1pz/9-1pz_config.xml";
	private static String URL_PRIFEX = "http://vv7.51zxw.net/class/proteus/";
	
    public static void main(String[] args) throws Exception {
        // Create an HttpClient with the ThreadSafeClientConnManager.
        // This connection manager must be used if more than one thread will
        // be using the HttpClient.                
        try {         
            int count = 0;
            int size=100;
            int runSize=0;
            int zmLen =zm.length-1;//标记长度，用于线程运行时做比较
            GetThread[] threads = new GetThread[size];
            for(int i=0;i<zm.length;i++) {
            	for(int j=0;j<zm.length;j++) {
            		String c = zm[i]+zm[j];            	
            		String uri = URL_PRIFEX+SECTION+c+"/"+SECTION+c+CONFIG;
            		HttpGet httpget = new HttpGet(uri);
            		httpget.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.114 Safari/537.36");
                    threads[runSize] = new GetThread(httpclient, httpget, count++);
                    runSize++;
                    //如果满足固定长度或者已经循环完成了，那就执行线程
                    if(runSize==size || (i == zmLen && j==zmLen )) {
                    	 // start the threads
                        for (int k = 0; k < runSize; k++) {
                            threads[k].start();
                        }

                        // join the threads
                        for (int k = 0; k < runSize; k++) {
                            threads[k].join();
                        }
                        runSize=0;
                    }
                    if(isFound) {
                    	return ;
                    }
            	}
            }
            /*
             // create an array of URIs to perform GETs on
            String[] urisToGet = {
                "http://hc.apache.org/",
                "http://hc.apache.org/httpcomponents-core-ga/",
                "http://hc.apache.org/httpcomponents-client-ga/",
            };
            // create a thread for each URI
            GetThread[] threads = new GetThread[urisToGet.length];
            for (int i = 0; i < threads.length; i++) {
                HttpGet httpget = new HttpGet(urisToGet[i]);
                threads[i] = new GetThread(httpclient, httpget, i + 1);
            }

            // start the threads
            for (int j = 0; j < threads.length; j++) {
                threads[j].start();
            }

            // join the threads
            for (int j = 0; j < threads.length; j++) {
                threads[j].join();
            }*/

        } finally {
            httpclient.close();
        }
    }

    /**
     * A thread that performs a GET.
     */
    static class GetThread extends Thread {

        private final CloseableHttpClient httpClient;
        private final HttpContext context;
        private final HttpGet httpget;
        private final int id;
        
        public GetThread(CloseableHttpClient httpClient, HttpGet httpget, int id) {
            this.httpClient = httpClient;
            this.context = new BasicHttpContext();
            this.httpget = httpget;
            this.id = id;
        }

        /**
         * Executes the GetMethod and prints some status information.
         */
        @Override
        public void run() {
            try {
                CloseableHttpResponse response = httpClient.execute(httpget, context);
                try {
                    System.out.println(id + " - get executed");
                    // get the response body as an array of bytes
                    StatusLine statusLine = response.getStatusLine();
                    int statusCode = statusLine.getStatusCode();
                    if(statusCode==404){
                    	return ;
                    }
                    isFound =true;
                    String url = httpget.getURI().toString();
                    System.out.println(id + " - about to get something from " + url);
                    System.out.println("目标地址："+url.replace(CONFIG,".html"));
                    HttpEntity entity = response.getEntity();
                    if (entity != null) {
                        //byte[] bytes = EntityUtils.toByteArray(entity);
                        //System.out.println(id + " - " + bytes.length + " bytes read");
                    	String content = EntityUtils.toString(entity, "gbk");
                    	System.out.println(content);
                    }
                } finally {
                    response.close();
                }
            } catch (Exception e) {
                System.out.println(id + " - error: " + e);
            }
        }

		

    }

}